#!/usr/bin/env python
# -*- encoding: utf-8 -*-
'''
@File    :   mail1.py
@Contact :   raogx.vip@hotmail.com
@License :   (C)Copyright 2017-2018, sungrow

@Modify Time      @Author    @Version    @Desciption
------------      -------    --------    -----------
2020/10/27 8:50   yyg      1.0         None
'''

import os
import smtplib
from email.mime.text import MIMEText
from email.header import Header
from email.mime.multipart import MIMEMultipart
from email.mime.application import MIMEApplication
from config import path

input_params = {
    "station_no": "3401220001",
    "area class": ["安徽省", "合肥市", "肥东县"],
    "email": "dataservice@sungrowpower.com"
}

send_user = 'dataservice@sungrowpower.com'
send_pwd = 'ch57Fk29pA8L'
receivers = [input_params['email']]
# file_path = '/home/ubuntu/data_collect/安徽省/合肥市/肥东县/3401220001/20201027102720/'
# file_name = '电站详细信息_3401220001_20201027102720.xlsx'
obj_path = "{0}/{1}/{2}".format(path, '/'.join(input_params['area class']), input_params['station_no'])
# noinspection PyBroadException
latest_up = [name for name in os.listdir(obj_path) if
             os.path.isdir(os.path.join(obj_path, name))][-1]  # 最新版本
file_path = "{0}/{1}".format(obj_path, latest_up)
file_name = [name for name in os.listdir(file_path) if name.split('.')[-1] == 'xlsx'][-1]

smtp_server = 'mail.sungrowpower.com'
smtp_port = 25

server = smtplib.SMTP(smtp_server, smtp_port)
server.login(send_user, send_pwd)

# 创建一个带附件的实例
message = MIMEMultipart()
message['From'] = Header("电站信息采集小程序", 'utf-8')
subject = '电站收集信息'
message['Subject'] = Header(subject, 'utf-8')

# 邮件正文内容
send_content = '{0}{1}{2}'.format('亲爱的电站信息采集小程序用户：\n\n',
                                  '         您好，您在小程序系统成功获取了电站信息文档，文档在附件中，请查收。\n\n',
                                  '感谢您对阳关电源的支持！')
message.attach(MIMEText(send_content, 'plain', 'utf-8'))
attachment = MIMEText(open(os.path.join(file_path, file_name), 'rb').read(), 'base64', 'gbk')
attachment.add_header('Content-Disposition', 'attachment', filename=('gbk', '', file_name))  # 附件1
message.attach(attachment)
try:
    server.sendmail(send_user, receivers, message.as_string())
    server.quit()
    print("邮件发送成功")
except smtplib.SMTPException:
    print("error: 无法发送邮件")
